* (bug 4035) Fix prev/next revision links on edit page
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contain the EditPage class
4 * @package MediaWiki
5 */
6
7 /**
8 * Splitting edit page/HTML interface from Article...
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
11 * interfaces.
12 *
13 * @package MediaWiki
14 */
15
16 class EditPage {
17 var $mArticle;
18 var $mTitle;
19 var $mMetaData = '';
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
23 var $formtype;
24 var $firsttime;
25 var $lastDelete;
26 var $mTokenOk = true;
27
28 # Form values
29 var $save = false, $preview = false, $diff = false;
30 var $minoredit = false, $watchthis = false, $recreate = false;
31 var $textbox1 = '', $textbox2 = '', $summary = '';
32 var $edittime = '', $section = '', $starttime = '';
33 var $oldid = 0, $editintro = '', $scrolltop = null;
34
35 /**
36 * @todo document
37 * @param $article
38 */
39 function EditPage( $article ) {
40 $this->mArticle =& $article;
41 global $wgTitle;
42 $this->mTitle =& $wgTitle;
43 }
44
45 /**
46 * This is the function that extracts metadata from the article body on the first view.
47 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
48 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
49 */
50 function extractMetaDataFromArticle () {
51 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
52 $this->mMetaData = '' ;
53 if ( !$wgUseMetadataEdit ) return ;
54 if ( $wgMetadataWhitelist == '' ) return ;
55 $s = '' ;
56 $t = $this->mArticle->getContent ( true ) ;
57
58 # MISSING : <nowiki> filtering
59
60 # Categories and language links
61 $t = explode ( "\n" , $t ) ;
62 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
63 $cat = $ll = array() ;
64 foreach ( $t AS $key => $x )
65 {
66 $y = trim ( strtolower ( $x ) ) ;
67 while ( substr ( $y , 0 , 2 ) == '[[' )
68 {
69 $y = explode ( ']]' , trim ( $x ) ) ;
70 $first = array_shift ( $y ) ;
71 $first = explode ( ':' , $first ) ;
72 $ns = array_shift ( $first ) ;
73 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
74 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
75 {
76 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
77 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
78 else $ll[] = $add ;
79 $x = implode ( ']]' , $y ) ;
80 $t[$key] = $x ;
81 $y = trim ( strtolower ( $x ) ) ;
82 }
83 }
84 }
85 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
86 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
87 $t = implode ( "\n" , $t ) ;
88
89 # Load whitelist
90 $sat = array () ; # stand-alone-templates; must be lowercase
91 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
92 $wl_article = new Article ( $wl_title ) ;
93 $wl = explode ( "\n" , $wl_article->getContent(true) ) ;
94 foreach ( $wl AS $x )
95 {
96 $isentry = false ;
97 $x = trim ( $x ) ;
98 while ( substr ( $x , 0 , 1 ) == '*' )
99 {
100 $isentry = true ;
101 $x = trim ( substr ( $x , 1 ) ) ;
102 }
103 if ( $isentry )
104 {
105 $sat[] = strtolower ( $x ) ;
106 }
107
108 }
109
110 # Templates, but only some
111 $t = explode ( '{{' , $t ) ;
112 $tl = array () ;
113 foreach ( $t AS $key => $x )
114 {
115 $y = explode ( '}}' , $x , 2 ) ;
116 if ( count ( $y ) == 2 )
117 {
118 $z = $y[0] ;
119 $z = explode ( '|' , $z ) ;
120 $tn = array_shift ( $z ) ;
121 if ( in_array ( strtolower ( $tn ) , $sat ) )
122 {
123 $tl[] = '{{' . $y[0] . '}}' ;
124 $t[$key] = $y[1] ;
125 $y = explode ( '}}' , $y[1] , 2 ) ;
126 }
127 else $t[$key] = '{{' . $x ;
128 }
129 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
130 else $t[$key] = $x ;
131 }
132 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
133 $t = implode ( '' , $t ) ;
134
135 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
136 $this->mArticle->mContent = $t ;
137 $this->mMetaData = $s ;
138 }
139
140 function submit() {
141 $this->edit();
142 }
143
144 /**
145 * This is the function that gets called for "action=edit". It
146 * sets up various member variables, then passes execution to
147 * another function, usually showEditForm()
148 *
149 * The edit form is self-submitting, so that when things like
150 * preview and edit conflicts occur, we get the same form back
151 * with the extra stuff added. Only when the final submission
152 * is made and all is well do we actually save and redirect to
153 * the newly-edited page.
154 */
155 function edit() {
156 global $wgOut, $wgUser, $wgRequest, $wgTitle;
157
158 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
159 return;
160
161 $fname = 'EditPage::edit';
162 wfProfileIn( $fname );
163 wfDebug( "$fname: enter\n" );
164
165 // this is not an article
166 $wgOut->setArticleFlag(false);
167
168 $this->importFormData( $wgRequest );
169 $this->firsttime = false;
170
171 if( $this->live ) {
172 $this->livePreview();
173 wfProfileOut( $fname );
174 return;
175 }
176
177 if ( ! $this->mTitle->userCanEdit() ) {
178 wfDebug( "$fname: user can't edit\n" );
179 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
180 wfProfileOut( $fname );
181 return;
182 }
183 wfDebug( "$fname: Checking blocks\n" );
184 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
185 # When previewing, don't check blocked state - will get caught at save time.
186 # Also, check when starting edition is done against slave to improve performance.
187 wfDebug( "$fname: user is blocked\n" );
188 $this->blockedIPpage();
189 wfProfileOut( $fname );
190 return;
191 }
192 if ( !$wgUser->isAllowed('edit') ) {
193 if ( $wgUser->isAnon() ) {
194 wfDebug( "$fname: user must log in\n" );
195 $this->userNotLoggedInPage();
196 wfProfileOut( $fname );
197 return;
198 } else {
199 wfDebug( "$fname: read-only page\n" );
200 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
201 wfProfileOut( $fname );
202 return;
203 }
204 }
205 if ( wfReadOnly() ) {
206 wfDebug( "$fname: read-only mode is engaged\n" );
207 if( $this->save || $this->preview ) {
208 $this->formtype = 'preview';
209 } else if ( $this->diff ) {
210 $this->formtype = 'diff';
211 } else {
212 $wgOut->readOnlyPage( $this->mArticle->getContent( true ) );
213 wfProfileOut( $fname );
214 return;
215 }
216 } else {
217 if ( $this->save ) {
218 $this->formtype = 'save';
219 } else if ( $this->preview ) {
220 $this->formtype = 'preview';
221 } else if ( $this->diff ) {
222 $this->formtype = 'diff';
223 } else { # First time through
224 $this->firsttime = true;
225 if( $this->previewOnOpen() ) {
226 $this->formtype = 'preview';
227 } else {
228 $this->extractMetaDataFromArticle () ;
229 $this->formtype = 'initial';
230 }
231 }
232 }
233
234 wfProfileIn( "$fname-business-end" );
235
236 $this->isConflict = false;
237 // css / js subpages of user pages get a special treatment
238 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
239
240 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
241 * no matter it's current state
242 */
243 $this->deletedSinceEdit = false;
244 if ( $this->edittime != '' ) {
245 /* Note that we rely on logging table, which hasn't been always there,
246 * but that doesn't matter, because this only applies to brand new
247 * deletes. This is done on every preview and save request. Move it further down
248 * to only perform it on saves
249 */
250 if ( $this->mTitle->isDeleted() ) {
251 $this->lastDelete = $this->getLastDelete();
252 if ( !is_null($this->lastDelete) ) {
253 $deletetime = $this->lastDelete->log_timestamp;
254 if ( ($deletetime - $this->starttime) > 0 ) {
255 $this->deletedSinceEdit = true;
256 }
257 }
258 }
259 }
260
261 if(!$this->mTitle->getArticleID() && ('initial' == $this->formtype || $this->firsttime )) { # new article
262 $this->showIntro();
263 }
264 if( $this->mTitle->isTalkPage() ) {
265 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
266 }
267
268 # Attempt submission here. This will check for edit conflicts,
269 # and redundantly check for locked database, blocked IPs, etc.
270 # that edit() already checked just in case someone tries to sneak
271 # in the back door with a hand-edited submission URL.
272
273 if ( 'save' == $this->formtype ) {
274 if ( !$this->attemptSave() ) {
275 wfProfileOut( "$fname-business-end" );
276 wfProfileOut( $fname );
277 return;
278 }
279 }
280
281 # First time through: get contents, set time for conflict
282 # checking, etc.
283 if ( 'initial' == $this->formtype || $this->firsttime ) {
284 $this->initialiseForm();
285 }
286
287 $this->showEditForm();
288 wfProfileOut( "$fname-business-end" );
289 wfProfileOut( $fname );
290 }
291
292 /**
293 * Return true if this page should be previewed when the edit form
294 * is initially opened.
295 * @return bool
296 * @access private
297 */
298 function previewOnOpen() {
299 global $wgUser;
300 return $wgUser->getOption( 'previewonfirst' ) ||
301 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
302 !$this->mTitle->exists() );
303 }
304
305 /**
306 * @todo document
307 */
308 function importFormData( &$request ) {
309 global $wgLang ;
310 $fname = 'EditPage::importFormData';
311 wfProfileIn( $fname );
312
313 if( $request->wasPosted() ) {
314 # These fields need to be checked for encoding.
315 # Also remove trailing whitespace, but don't remove _initial_
316 # whitespace from the text boxes. This may be significant formatting.
317 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
318 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
319 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
320 # Truncate for whole multibyte characters. +5 bytes for ellipsis
321 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
322
323 $this->edittime = $request->getVal( 'wpEdittime' );
324 $this->starttime = $request->getVal( 'wpStarttime' );
325
326 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
327
328 if( is_null( $this->edittime ) ) {
329 # If the form is incomplete, force to preview.
330 wfDebug( "$fname: Form data appears to be incomplete\n" );
331 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
332 $this->preview = true;
333 } else {
334 $this->preview = $request->getCheck( 'wpPreview' );
335 $this->diff = $request->getCheck( 'wpDiff' );
336
337 if( !$this->preview ) {
338 if ( $this->tokenOk( $request ) ) {
339 # Some browsers will not report any submit button
340 # if the user hits enter in the comment box.
341 # The unmarked state will be assumed to be a save,
342 # if the form seems otherwise complete.
343 wfDebug( "$fname: Passed token check.\n" );
344 } else {
345 # Page might be a hack attempt posted from
346 # an external site. Preview instead of saving.
347 wfDebug( "$fname: Failed token check; forcing preview\n" );
348 $this->preview = true;
349 }
350 }
351 }
352 $this->save = ! ( $this->preview OR $this->diff );
353 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
354 $this->edittime = null;
355 }
356
357 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
358 $this->starttime = null;
359 }
360
361 $this->recreate = $request->getCheck( 'wpRecreate' );
362
363 $this->minoredit = $request->getCheck( 'wpMinoredit' );
364 $this->watchthis = $request->getCheck( 'wpWatchthis' );
365 } else {
366 # Not a posted form? Start with nothing.
367 wfDebug( "$fname: Not a posted form.\n" );
368 $this->textbox1 = '';
369 $this->textbox2 = '';
370 $this->mMetaData = '';
371 $this->summary = '';
372 $this->edittime = '';
373 $this->starttime = wfTimestampNow();
374 $this->preview = false;
375 $this->save = false;
376 $this->diff = false;
377 $this->minoredit = false;
378 $this->watchthis = false;
379 $this->recreate = false;
380 }
381
382 $this->oldid = $request->getInt( 'oldid' );
383
384 # Section edit can come from either the form or a link
385 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
386
387 $this->live = $request->getCheck( 'live' );
388 $this->editintro = $request->getText( 'editintro' );
389
390 wfProfileOut( $fname );
391 }
392
393 /**
394 * Make sure the form isn't faking a user's credentials.
395 *
396 * @param WebRequest $request
397 * @return bool
398 * @access private
399 */
400 function tokenOk( &$request ) {
401 global $wgUser;
402 if( $wgUser->isAnon() ) {
403 # Anonymous users may not have a session
404 # open. Don't tokenize.
405 $this->mTokenOk = true;
406 } else {
407 $this->mTokenOk = $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
408 }
409 return $this->mTokenOk;
410 }
411
412 function showIntro() {
413 global $wgOut, $wgUser;
414 $addstandardintro=true;
415 if($this->editintro) {
416 $introtitle=Title::newFromText($this->editintro);
417 if(isset($introtitle) && $introtitle->userCanRead()) {
418 $rev=Revision::newFromTitle($introtitle);
419 if($rev) {
420 $wgOut->addWikiText($rev->getText());
421 $addstandardintro=false;
422 }
423 }
424 }
425 if($addstandardintro) {
426 if ( $wgUser->isLoggedIn() )
427 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
428 else
429 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
430 }
431 }
432
433 /**
434 * Attempt submission
435 * @return bool false if output is done, true if the rest of the form should be displayed
436 */
437 function attemptSave() {
438 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
439
440 $fname = 'EditPage::attemptSave';
441 wfProfileIn( $fname );
442 wfProfileIn( "$fname-checks" );
443
444 # Reintegrate metadata
445 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
446 $this->mMetaData = '' ;
447
448 # Check for spam
449 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
450 $this->spamPage ( $matches[0] );
451 wfProfileOut( "$fname-checks" );
452 wfProfileOut( $fname );
453 return false;
454 }
455 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
456 # Error messages or other handling should be performed by the filter function
457 wfProfileOut( $fname );
458 wfProfileOut( "$fname-checks" );
459 return false;
460 }
461 if ( !wfRunHooks( 'EditFilter', array( &$this, $this->textbox1, $this->section ) ) ) {
462 # Error messages or other handling should be performed by the filter function
463 wfProfileOut( $fname );
464 wfProfileOut( "$fname-checks" );
465 return false;
466 }
467 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
468 # Check block state against master, thus 'false'.
469 $this->blockedIPpage();
470 wfProfileOut( "$fname-checks" );
471 wfProfileOut( $fname );
472 return false;
473 }
474
475 if ( !$wgUser->isAllowed('edit') ) {
476 if ( $wgUser->isAnon() ) {
477 $this->userNotLoggedInPage();
478 wfProfileOut( "$fname-checks" );
479 wfProfileOut( $fname );
480 return false;
481 }
482 else {
483 $wgOut->readOnlyPage();
484 wfProfileOut( "$fname-checks" );
485 wfProfileOut( $fname );
486 return false;
487 }
488 }
489
490 if ( wfReadOnly() ) {
491 $wgOut->readOnlyPage();
492 wfProfileOut( "$fname-checks" );
493 wfProfileOut( $fname );
494 return false;
495 }
496 if ( $wgUser->pingLimiter() ) {
497 $wgOut->rateLimited();
498 wfProfileOut( "$fname-checks" );
499 wfProfileOut( $fname );
500 return false;
501 }
502
503 # If the article has been deleted while editing, don't save it without
504 # confirmation
505 if ( $this->deletedSinceEdit && !$this->recreate ) {
506 wfProfileOut( "$fname-checks" );
507 wfProfileOut( $fname );
508 return true;
509 }
510
511 wfProfileOut( "$fname-checks" );
512
513 # If article is new, insert it.
514 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
515 if ( 0 == $aid ) {
516 # Don't save a new article if it's blank.
517 if ( ( '' == $this->textbox1 ) ) {
518 $wgOut->redirect( $this->mTitle->getFullURL() );
519 wfProfileOut( $fname );
520 return false;
521 }
522
523 $isComment=($this->section=='new');
524 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
525 $this->minoredit, $this->watchthis, false, $isComment);
526
527 wfProfileOut( $fname );
528 return false;
529 }
530
531 # Article exists. Check for edit conflict.
532
533 $this->mArticle->clear(); # Force reload of dates, etc.
534 $this->mArticle->forUpdate( true ); # Lock the article
535
536 if( ( $this->section != 'new' ) &&
537 ($this->mArticle->getTimestamp() != $this->edittime ) )
538 {
539 $this->isConflict = true;
540 }
541 $userid = $wgUser->getID();
542
543 if ( $this->isConflict) {
544 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
545 $this->mArticle->getTimestamp() . "'\n" );
546 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
547 }
548 else {
549 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
550 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
551 }
552 if( is_null( $text ) ) {
553 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
554 $this->isConflict = true;
555 $text = $this->textbox1;
556 }
557
558 # Suppress edit conflict with self, except for section edits where merging is required.
559 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
560 wfDebug( "Suppressing edit conflict, same user.\n" );
561 $this->isConflict = false;
562 } else {
563 # switch from section editing to normal editing in edit conflict
564 if($this->isConflict) {
565 # Attempt merge
566 if( $this->mergeChangesInto( $text ) ){
567 // Successful merge! Maybe we should tell the user the good news?
568 $this->isConflict = false;
569 wfDebug( "Suppressing edit conflict, successful merge.\n" );
570 } else {
571 $this->section = '';
572 $this->textbox1 = $text;
573 wfDebug( "Keeping edit conflict, failed merge.\n" );
574 }
575 }
576 }
577
578 if ( $this->isConflict ) {
579 wfProfileOut( $fname );
580 return true;
581 }
582
583 # All's well
584 wfProfileIn( "$fname-sectionanchor" );
585 $sectionanchor = '';
586 if( $this->section == 'new' ) {
587 if( $this->summary != '' ) {
588 $sectionanchor = $this->sectionAnchor( $this->summary );
589 }
590 } elseif( $this->section != '' ) {
591 # Try to get a section anchor from the section source, redirect to edited section if header found
592 # XXX: might be better to integrate this into Article::replaceSection
593 # for duplicate heading checking and maybe parsing
594 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
595 # we can't deal with anchors, includes, html etc in the header for now,
596 # headline would need to be parsed to improve this
597 if($hasmatch and strlen($matches[2]) > 0) {
598 $sectionanchor = $this->sectionAnchor( $matches[2] );
599 }
600 }
601 wfProfileOut( "$fname-sectionanchor" );
602
603 // Save errors may fall down to the edit form, but we've now
604 // merged the section into full text. Clear the section field
605 // so that later submission of conflict forms won't try to
606 // replace that into a duplicated mess.
607 $this->textbox1 = $text;
608 $this->section = '';
609
610 # update the article here
611 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
612 $this->watchthis, '', $sectionanchor ) ) {
613 wfProfileOut( $fname );
614 return false;
615 } else {
616 $this->isConflict = true;
617 }
618 wfProfileOut( $fname );
619 return true;
620 }
621
622 /**
623 * Initialise form fields in the object
624 * Called on the first invocation, e.g. when a user clicks an edit link
625 */
626 function initialiseForm() {
627 $this->edittime = $this->mArticle->getTimestamp();
628 $this->textbox1 = $this->mArticle->getContent( true );
629 $this->summary = '';
630 wfProxyCheck();
631 }
632
633 /**
634 * Send the edit form and related headers to $wgOut
635 * @param $formCallback Optional callable that takes an OutputPage
636 * parameter; will be called during form output
637 * near the top, for captchas and the like.
638 */
639 function showEditForm( $formCallback=null ) {
640 global $wgOut, $wgUser, $wgAllowAnonymousMinor, $wgLang, $wgContLang;
641
642 $fname = 'EditPage::showEditForm';
643 wfProfileIn( $fname );
644
645 $sk =& $wgUser->getSkin();
646
647 $wgOut->setRobotpolicy( 'noindex,nofollow' );
648
649 # Enabled article-related sidebar, toplinks, etc.
650 $wgOut->setArticleRelated( true );
651
652 if ( $this->isConflict ) {
653 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
654 $wgOut->setPageTitle( $s );
655 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
656
657 $this->textbox2 = $this->textbox1;
658 $this->textbox1 = $this->mArticle->getContent( true );
659 $this->edittime = $this->mArticle->getTimestamp();
660 } else {
661
662 if( $this->section != '' ) {
663 if( $this->section == 'new' ) {
664 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
665 } else {
666 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
667 if( !$this->preview && !$this->diff ) {
668 preg_match( "/^(=+)(.+)\\1/mi",
669 $this->textbox1,
670 $matches );
671 if( !empty( $matches[2] ) ) {
672 $this->summary = "/* ". trim($matches[2])." */ ";
673 }
674 }
675 }
676 } else {
677 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
678 }
679 $wgOut->setPageTitle( $s );
680 if ( !$this->checkUnicodeCompliantBrowser() ) {
681 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
682 }
683 if ( isset( $this->mArticle )
684 && isset( $this->mArticle->mRevision )
685 && !$this->mArticle->mRevision->isCurrent() ) {
686 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
687 $wgOut->addWikiText( wfMsg( 'editingold' ) );
688 }
689 }
690
691 if( wfReadOnly() ) {
692 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
693 } else if ( $this->isCssJsSubpage and 'preview' != $this->formtype) {
694 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
695 }
696 if( $this->mTitle->isProtected('edit') ) {
697 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
698 }
699
700 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
701 if( $kblength > 29 ) {
702 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
703 }
704
705 $rows = $wgUser->getOption( 'rows' );
706 $cols = $wgUser->getOption( 'cols' );
707
708 $ew = $wgUser->getOption( 'editwidth' );
709 if ( $ew ) $ew = " style=\"width:100%\"";
710 else $ew = '';
711
712 $q = 'action=submit';
713 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
714 $action = $this->mTitle->escapeLocalURL( $q );
715
716 $summary = wfMsg('summary');
717 $subject = wfMsg('subject');
718 $minor = wfMsg('minoredit');
719 $watchthis = wfMsg ('watchthis');
720 $save = wfMsg('savearticle');
721 $prev = wfMsg('showpreview');
722 $diff = wfMsg('showdiff');
723
724 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
725 wfMsg('cancel') );
726 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
727 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
728 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
729 htmlspecialchars( wfMsg( 'newwindow' ) );
730
731 global $wgRightsText;
732 $copywarn = "<div id=\"editpage-copywarn\">\n" .
733 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
734 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
735 $wgRightsText ) . "\n</div>";
736
737 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
738 # prepare toolbar for edit buttons
739 $toolbar = $this->getEditToolbar();
740 } else {
741 $toolbar = '';
742 }
743
744 // activate checkboxes if user wants them to be always active
745 if( !$this->preview && !$this->diff ) {
746 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis = true;
747 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
748
749 // activate checkbox also if user is already watching the page,
750 // require wpWatchthis to be unset so that second condition is not
751 // checked unnecessarily
752 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
753 }
754
755 $minoredithtml = '';
756
757 if ( $wgUser->isLoggedIn() || $wgAllowAnonymousMinor ) {
758 $minoredithtml =
759 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
760 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
761 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
762 }
763
764 $watchhtml = '';
765
766 if ( $wgUser->isLoggedIn() ) {
767 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
768 ($this->watchthis?" checked='checked'":"").
769 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
770 "<label for='wpWatchthis' title=\"" .
771 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
772 }
773
774 $checkboxhtml = $minoredithtml . $watchhtml;
775
776 if ( 'preview' == $this->formtype && $wgUser->getOption( 'previewontop' ) ) {
777 $this->showPreview();
778 }
779 if ( 'diff' == $this->formtype ) {
780 if ( $wgUser->getOption('previewontop' ) ) {
781 $wgOut->addHTML( $this->getDiff() );
782 }
783 }
784
785
786 # if this is a comment, show a subject line at the top, which is also the edit summary.
787 # Otherwise, show a summary field at the bottom
788 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
789 if( $this->section == 'new' ) {
790 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span> <div class='editOptions'><input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
791 $editsummary = '';
792 } else {
793 $commentsubject = '';
794 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span> <div class='editOptions'><input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
795 }
796
797 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
798 if( !$this->preview && !$this->diff ) {
799 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
800 }
801 $templates = $this->getTemplatesUsed();
802
803 global $wgLivePreview;
804 if ( $wgLivePreview ) {
805 $liveOnclick = $this->doLivePreviewScript();
806 } else {
807 $liveOnclick = '';
808 }
809
810 global $wgUseMetadataEdit ;
811 if ( $wgUseMetadataEdit ) {
812 $metadata = $this->mMetaData ;
813 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
814 $helppage = Title::newFromText( wfMsg( "metadata_page" ) ) ;
815 $top = wfMsg( 'metadata', $helppage->getInternalURL() );
816 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
817 }
818 else $metadata = "" ;
819
820 $hidden = '';
821 $recreate = '';
822 if ($this->deletedSinceEdit) {
823 if ( 'save' != $this->formtype ) {
824 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
825 } else {
826 // Hide the toolbar and edit area, use can click preview to get it back
827 // Add an confirmation checkbox and explanation.
828 $toolbar = '';
829 $hidden = 'type="hidden" style="display:none;"';
830 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
831 $recreate .=
832 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
833 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
834 }
835 }
836
837 $safemodehtml = $this->checkUnicodeCompliantBrowser()
838 ? ""
839 : "<input type='hidden' name=\"safemode\" value='1' />\n";
840
841 $wgOut->addHTML( <<<END
842 {$toolbar}
843 <form id="editform" name="editform" method="post" action="$action"
844 enctype="multipart/form-data">
845 END
846 );
847 if( is_callable( $formCallback ) ) {
848 call_user_func_array( $formCallback, array( &$wgOut ) );
849 }
850 $wgOut->addHTML( <<<END
851 $recreate
852 {$commentsubject}
853 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
854 cols='{$cols}'{$ew} $hidden>
855 END
856 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
857 "
858 </textarea><br />
859 {$metadata}
860 {$editsummary}
861 {$checkboxhtml}
862 {$safemodehtml}
863 <div class='editButtons'>
864 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
865 " title=\"".wfMsg('tooltip-save')."\"/>
866 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
867 " title=\"".wfMsg('tooltip-preview')."\"/>
868 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
869 " title=\"".wfMsg('tooltip-diff')."\"/> <span class='editHelp'>{$cancel} | {$edithelp}</span></div>
870 </div>
871 <div class='templatesUsed'>
872 {$templates}
873 </div>
874 " );
875 $wgOut->addWikiText( $copywarn );
876 $wgOut->addHTML( "
877 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
878 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
879 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
880 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
881
882 if ( $wgUser->isLoggedIn() ) {
883 /**
884 * To make it harder for someone to slip a user a page
885 * which submits an edit form to the wiki without their
886 * knowledge, a random token is associated with the login
887 * session. If it's not passed back with the submission,
888 * we won't save the page, or render user JavaScript and
889 * CSS previews.
890 */
891 $token = htmlspecialchars( $wgUser->editToken() );
892 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
893 }
894
895
896 if ( $this->isConflict ) {
897 require_once( "DifferenceEngine.php" );
898 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
899
900 $de = new DifferenceEngine( $this->mTitle );
901 $de->setText( $this->textbox2, $this->textbox1 );
902 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
903
904 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
905 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
906 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
907 }
908 $wgOut->addHTML( "</form>\n" );
909 if ( $this->formtype == 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
910 $this->showPreview();
911 }
912 if ( $this->formtype == 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
913 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
914 $wgOut->addHTML( $this->getDiff() );
915 }
916
917 wfProfileOut( $fname );
918 }
919
920 /**
921 * Append preview output to $wgOut.
922 * Includes category rendering if this is a category page.
923 * @access private
924 */
925 function showPreview() {
926 global $wgOut;
927 $wgOut->addHTML( '<div id="wikiPreview">' );
928 if($this->mTitle->getNamespace() == NS_CATEGORY) {
929 $this->mArticle->openShowCategory();
930 }
931 $previewOutput = $this->getPreviewText();
932 $wgOut->addHTML( $previewOutput );
933 if($this->mTitle->getNamespace() == NS_CATEGORY) {
934 $this->mArticle->closeShowCategory();
935 }
936 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
937 $wgOut->addHTML( '</div>' );
938 }
939
940 /**
941 * Prepare a list of templates used by this page. Returns HTML.
942 */
943 function getTemplatesUsed() {
944 global $wgUser;
945
946 $fname = 'EditPage::getTemplatesUsed';
947 wfProfileIn( $fname );
948
949 $sk =& $wgUser->getSkin();
950
951 $templates = '';
952 $articleTemplates = $this->mArticle->getUsedTemplates();
953 if ( count( $articleTemplates ) > 0 ) {
954 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
955 foreach ( $articleTemplates as $tpl ) {
956 if ( $titleObj = Title::makeTitle( NS_TEMPLATE, $tpl ) ) {
957 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
958 }
959 }
960 $templates .= '</ul>';
961 }
962 wfProfileOut( $fname );
963 return $templates;
964 }
965
966 /**
967 * Live Preview lets us fetch rendered preview page content and
968 * add it to the page without refreshing the whole page.
969 * If not supported by the browser it will fall through to the normal form
970 * submission method.
971 *
972 * This function outputs a script tag to support live preview, and
973 * returns an onclick handler which should be added to the attributes
974 * of the preview button
975 */
976 function doLivePreviewScript() {
977 global $wgStylePath, $wgJsMimeType, $wgOut;
978 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
979 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
980 '"></script>' . "\n" );
981 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
982 return 'onclick="return !livePreview('.
983 'getElementById(\'wikiPreview\'),' .
984 'editform.wpTextbox1.value,' .
985 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
986 }
987
988 function getLastDelete() {
989 $dbr =& wfGetDB( DB_SLAVE );
990 $fname = 'EditPage::getLastDelete';
991 $res = $dbr->select(
992 array( 'logging', 'user' ),
993 array( 'log_type',
994 'log_action',
995 'log_timestamp',
996 'log_user',
997 'log_namespace',
998 'log_title',
999 'log_comment',
1000 'log_params',
1001 'user_name', ),
1002 array( 'log_namespace' => $this->mTitle->getNamespace(),
1003 'log_title' => $this->mTitle->getDBkey(),
1004 'log_type' => 'delete',
1005 'log_action' => 'delete',
1006 'user_id=log_user' ),
1007 $fname,
1008 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1009
1010 if($dbr->numRows($res) == 1) {
1011 while ( $x = $dbr->fetchObject ( $res ) )
1012 $data = $x;
1013 $dbr->freeResult ( $res ) ;
1014 } else {
1015 $data = null;
1016 }
1017 return $data;
1018 }
1019
1020 /**
1021 * @todo document
1022 */
1023 function getPreviewText() {
1024 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
1025
1026 $fname = 'EditPage::getPreviewText';
1027 wfProfileIn( $fname );
1028
1029 if ( $this->mTokenOk ) {
1030 $msg = 'previewnote';
1031 } else {
1032 $msg = 'session_fail_preview';
1033 }
1034 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1035 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1036 if ( $this->isConflict ) {
1037 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1038 }
1039
1040 $parserOptions = ParserOptions::newFromUser( $wgUser );
1041 $parserOptions->setEditSection( false );
1042
1043 # don't parse user css/js, show message about preview
1044 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1045
1046 if ( $this->isCssJsSubpage ) {
1047 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1048 $previewtext = wfMsg('usercsspreview');
1049 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1050 $previewtext = wfMsg('userjspreview');
1051 }
1052 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1053 $wgOut->addHTML( $parserOutput->mText );
1054 wfProfileOut( $fname );
1055 return $previewhead;
1056 } else {
1057 # if user want to see preview when he edit an article
1058 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
1059 $this->textbox1 = $this->mArticle->getContent(true);
1060 }
1061
1062 $toparse = $this->textbox1;
1063
1064 # If we're adding a comment, we need to show the
1065 # summary as the headline
1066 if($this->section=="new" && $this->summary!="") {
1067 $toparse="== {$this->summary} ==\n\n".$toparse;
1068 }
1069
1070 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1071
1072 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1073 $wgTitle, $parserOptions );
1074
1075 $previewHTML = $parserOutput->mText;
1076
1077 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
1078 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
1079
1080 wfProfileOut( $fname );
1081 return $previewhead . $previewHTML;
1082 }
1083 }
1084
1085 /**
1086 * @todo document
1087 */
1088 function blockedIPpage() {
1089 global $wgOut, $wgUser, $wgContLang;
1090
1091 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
1092 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1093 $wgOut->setArticleRelated( false );
1094
1095 $id = $wgUser->blockedBy();
1096 $reason = $wgUser->blockedFor();
1097 $ip = wfGetIP();
1098
1099 if ( is_numeric( $id ) ) {
1100 $name = User::whoIs( $id );
1101 } else {
1102 $name = $id;
1103 }
1104 $link = '[[' . $wgContLang->getNsText( NS_USER ) .
1105 ":{$name}|{$name}]]";
1106
1107 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
1108 $wgOut->returnToMain( false );
1109 }
1110
1111 /**
1112 * @todo document
1113 */
1114 function userNotLoggedInPage() {
1115 global $wgOut;
1116
1117 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1118 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1119 $wgOut->setArticleRelated( false );
1120
1121 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1122 $wgOut->returnToMain( false );
1123 }
1124
1125 /**
1126 * @todo document
1127 */
1128 function spamPage ( $match = false )
1129 {
1130 global $wgOut;
1131 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1132 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1133 $wgOut->setArticleRelated( false );
1134
1135 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1136 if ( $match ) {
1137 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1138 }
1139 $wgOut->returnToMain( false );
1140 }
1141
1142 /**
1143 * @access private
1144 * @todo document
1145 */
1146 function mergeChangesInto( &$editText ){
1147 $fname = 'EditPage::mergeChangesInto';
1148 wfProfileIn( $fname );
1149
1150 $db =& wfGetDB( DB_MASTER );
1151
1152 // This is the revision the editor started from
1153 $baseRevision = Revision::loadFromTimestamp(
1154 $db, $this->mArticle->mTitle, $this->edittime );
1155 if( is_null( $baseRevision ) ) {
1156 wfProfileOut( $fname );
1157 return false;
1158 }
1159 $baseText = $baseRevision->getText();
1160
1161 // The current state, we want to merge updates into it
1162 $currentRevision = Revision::loadFromTitle(
1163 $db, $this->mArticle->mTitle );
1164 if( is_null( $currentRevision ) ) {
1165 wfProfileOut( $fname );
1166 return false;
1167 }
1168 $currentText = $currentRevision->getText();
1169
1170 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1171 $editText = $result;
1172 wfProfileOut( $fname );
1173 return true;
1174 } else {
1175 wfProfileOut( $fname );
1176 return false;
1177 }
1178 }
1179
1180 /**
1181 * Check if the browser is on a blacklist of user-agents known to
1182 * mangle UTF-8 data on form submission. Returns true if Unicode
1183 * should make it through, false if it's known to be a problem.
1184 * @return bool
1185 * @access private
1186 */
1187 function checkUnicodeCompliantBrowser() {
1188 global $wgBrowserBlackList;
1189 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1190 // No User-Agent header sent? Trust it by default...
1191 return true;
1192 }
1193 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1194 foreach ( $wgBrowserBlackList as $browser ) {
1195 if ( preg_match($browser, $currentbrowser) ) {
1196 return false;
1197 }
1198 }
1199 return true;
1200 }
1201
1202 /**
1203 * Format an anchor fragment as it would appear for a given section name
1204 * @param string $text
1205 * @return string
1206 * @access private
1207 */
1208 function sectionAnchor( $text ) {
1209 $headline = Sanitizer::decodeCharReferences( $text );
1210 # strip out HTML
1211 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1212 $headline = trim( $headline );
1213 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1214 $replacearray = array(
1215 '%3A' => ':',
1216 '%' => '.'
1217 );
1218 return str_replace(
1219 array_keys( $replacearray ),
1220 array_values( $replacearray ),
1221 $sectionanchor );
1222 }
1223
1224 /**
1225 * Shows a bulletin board style toolbar for common editing functions.
1226 * It can be disabled in the user preferences.
1227 * The necessary JavaScript code can be found in style/wikibits.js.
1228 */
1229 function getEditToolbar() {
1230 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1231
1232 /**
1233 * toolarray an array of arrays which each include the filename of
1234 * the button image (without path), the opening tag, the closing tag,
1235 * and optionally a sample text that is inserted between the two when no
1236 * selection is highlighted.
1237 * The tip text is shown when the user moves the mouse over the button.
1238 *
1239 * Already here are accesskeys (key), which are not used yet until someone
1240 * can figure out a way to make them work in IE. However, we should make
1241 * sure these keys are not defined on the edit page.
1242 */
1243 $toolarray=array(
1244 array( 'image'=>'button_bold.png',
1245 'open' => "\'\'\'",
1246 'close' => "\'\'\'",
1247 'sample'=> wfMsg('bold_sample'),
1248 'tip' => wfMsg('bold_tip'),
1249 'key' => 'B'
1250 ),
1251 array( 'image'=>'button_italic.png',
1252 'open' => "\'\'",
1253 'close' => "\'\'",
1254 'sample'=> wfMsg('italic_sample'),
1255 'tip' => wfMsg('italic_tip'),
1256 'key' => 'I'
1257 ),
1258 array( 'image'=>'button_link.png',
1259 'open' => '[[',
1260 'close' => ']]',
1261 'sample'=> wfMsg('link_sample'),
1262 'tip' => wfMsg('link_tip'),
1263 'key' => 'L'
1264 ),
1265 array( 'image'=>'button_extlink.png',
1266 'open' => '[',
1267 'close' => ']',
1268 'sample'=> wfMsg('extlink_sample'),
1269 'tip' => wfMsg('extlink_tip'),
1270 'key' => 'X'
1271 ),
1272 array( 'image'=>'button_headline.png',
1273 'open' => "\\n== ",
1274 'close' => " ==\\n",
1275 'sample'=> wfMsg('headline_sample'),
1276 'tip' => wfMsg('headline_tip'),
1277 'key' => 'H'
1278 ),
1279 array( 'image'=>'button_image.png',
1280 'open' => '[['.$wgLang->getNsText(NS_IMAGE).":",
1281 'close' => ']]',
1282 'sample'=> wfMsg('image_sample'),
1283 'tip' => wfMsg('image_tip'),
1284 'key' => 'D'
1285 ),
1286 array( 'image' =>'button_media.png',
1287 'open' => '[['.$wgLang->getNsText(NS_MEDIA).':',
1288 'close' => ']]',
1289 'sample'=> wfMsg('media_sample'),
1290 'tip' => wfMsg('media_tip'),
1291 'key' => 'M'
1292 ),
1293 array( 'image' =>'button_math.png',
1294 'open' => "\\<math\\>",
1295 'close' => "\\</math\\>",
1296 'sample'=> wfMsg('math_sample'),
1297 'tip' => wfMsg('math_tip'),
1298 'key' => 'C'
1299 ),
1300 array( 'image' =>'button_nowiki.png',
1301 'open' => "\\<nowiki\\>",
1302 'close' => "\\</nowiki\\>",
1303 'sample'=> wfMsg('nowiki_sample'),
1304 'tip' => wfMsg('nowiki_tip'),
1305 'key' => 'N'
1306 ),
1307 array( 'image' =>'button_sig.png',
1308 'open' => '--~~~~',
1309 'close' => '',
1310 'sample'=> '',
1311 'tip' => wfMsg('sig_tip'),
1312 'key' => 'Y'
1313 ),
1314 array( 'image' =>'button_hr.png',
1315 'open' => "\\n----\\n",
1316 'close' => '',
1317 'sample'=> '',
1318 'tip' => wfMsg('hr_tip'),
1319 'key' => 'R'
1320 )
1321 );
1322 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1323
1324 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1325 foreach($toolarray as $tool) {
1326
1327 $image=$wgStylePath.'/common/images/'.$tool['image'];
1328 $open=$tool['open'];
1329 $close=$tool['close'];
1330 $sample = wfEscapeJsString( $tool['sample'] );
1331
1332 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1333 // Older browsers show a "speedtip" type message only for ALT.
1334 // Ideally these should be different, realistically they
1335 // probably don't need to be.
1336 $tip = wfEscapeJsString( $tool['tip'] );
1337
1338 #$key = $tool["key"];
1339
1340 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1341 }
1342
1343 $toolbar.="document.writeln(\"</div>\");\n";
1344 $toolbar.="/*]]>*/\n</script>";
1345 return $toolbar;
1346 }
1347
1348 /**
1349 * Output preview text only. This can be sucked into the edit page
1350 * via JavaScript, and saves the server time rendering the skin as
1351 * well as theoretically being more robust on the client (doesn't
1352 * disturb the edit box's undo history, won't eat your text on
1353 * failure, etc).
1354 *
1355 * @todo This doesn't include category or interlanguage links.
1356 * Would need to enhance it a bit, maybe wrap them in XML
1357 * or something... that might also require more skin
1358 * initialization, so check whether that's a problem.
1359 */
1360 function livePreview() {
1361 global $wgOut;
1362 $wgOut->disable();
1363 header( 'Content-type: text/xml' );
1364 header( 'Cache-control: no-cache' );
1365 # FIXME
1366 echo $this->getPreviewText( false, false );
1367 }
1368
1369
1370 /**
1371 * Get a diff between the current contents of the edit box and the
1372 * version of the page we're editing from.
1373 *
1374 * If this is a section edit, we'll replace the section as for final
1375 * save and then make a comparison.
1376 *
1377 * @return string HTML
1378 */
1379 function getDiff() {
1380 global $wgUser;
1381
1382 require_once( 'DifferenceEngine.php' );
1383 $oldtext = $this->mArticle->fetchContent();
1384 $newtext = $this->mArticle->replaceSection(
1385 $this->section, $this->textbox1, $this->summary, $this->edittime );
1386 $oldtitle = wfMsg( 'currentrev' );
1387 $newtitle = wfMsg( 'yourtext' );
1388 if ( $oldtext !== false || $newtext != '' ) {
1389 $de = new DifferenceEngine( $this->mTitle );
1390 $de->setText( $oldtext, $newtext );
1391 $difftext = $de->getDiff( $oldtitle, $newtitle );
1392 } else {
1393 $difftext = '';
1394 }
1395
1396 return '<div id="wikiDiff">' . $difftext . '</div>';
1397 }
1398
1399 /**
1400 * Filter an input field through a Unicode de-armoring process if it
1401 * came from an old browser with known broken Unicode editing issues.
1402 *
1403 * @param WebRequest $request
1404 * @param string $field
1405 * @return string
1406 * @access private
1407 */
1408 function safeUnicodeInput( $request, $field ) {
1409 $text = rtrim( $request->getText( $field ) );
1410 return $request->getBool( 'safemode' )
1411 ? $this->unmakesafe( $text )
1412 : $text;
1413 }
1414
1415 /**
1416 * Filter an output field through a Unicode armoring process if it is
1417 * going to an old browser with known broken Unicode editing issues.
1418 *
1419 * @param string $text
1420 * @return string
1421 * @access private
1422 */
1423 function safeUnicodeOutput( $text ) {
1424 global $wgContLang;
1425 $codedText = $wgContLang->recodeForEdit( $text );
1426 return $this->checkUnicodeCompliantBrowser()
1427 ? $codedText
1428 : $this->makesafe( $codedText );
1429 }
1430
1431 /**
1432 * A number of web browsers are known to corrupt non-ASCII characters
1433 * in a UTF-8 text editing environment. To protect against this,
1434 * detected browsers will be served an armored version of the text,
1435 * with non-ASCII chars converted to numeric HTML character references.
1436 *
1437 * Preexisting such character references will have a 0 added to them
1438 * to ensure that round-trips do not alter the original data.
1439 *
1440 * @param string $invalue
1441 * @return string
1442 * @access private
1443 */
1444 function makesafe( $invalue ) {
1445 // Armor existing references for reversability.
1446 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1447
1448 $bytesleft = 0;
1449 $result = "";
1450 $working = 0;
1451 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1452 $bytevalue = ord( $invalue{$i} );
1453 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1454 $result .= chr( $bytevalue );
1455 $bytesleft = 0;
1456 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1457 $working = $working << 6;
1458 $working += ($bytevalue & 0x3F);
1459 $bytesleft--;
1460 if( $bytesleft <= 0 ) {
1461 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1462 }
1463 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1464 $working = $bytevalue & 0x1F;
1465 $bytesleft = 1;
1466 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1467 $working = $bytevalue & 0x0F;
1468 $bytesleft = 2;
1469 } else { //1111 0xxx
1470 $working = $bytevalue & 0x07;
1471 $bytesleft = 3;
1472 }
1473 }
1474 return $result;
1475 }
1476
1477 /**
1478 * Reverse the previously applied transliteration of non-ASCII characters
1479 * back to UTF-8. Used to protect data from corruption by broken web browsers
1480 * as listed in $wgBrowserBlackList.
1481 *
1482 * @param string $invalue
1483 * @return string
1484 * @access private
1485 */
1486 function unmakesafe( $invalue ) {
1487 $result = "";
1488 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1489 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1490 $i += 3;
1491 $hexstring = "";
1492 do {
1493 $hexstring .= $invalue{$i};
1494 $i++;
1495 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1496
1497 // Do some sanity checks. These aren't needed for reversability,
1498 // but should help keep the breakage down if the editor
1499 // breaks one of the entities whilst editing.
1500 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1501 $codepoint = hexdec($hexstring);
1502 $result .= codepointToUtf8( $codepoint );
1503 } else {
1504 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1505 }
1506 } else {
1507 $result .= substr( $invalue, $i, 1 );
1508 }
1509 }
1510 // reverse the transform that we made for reversability reasons.
1511 return strtr( $result, array( "&#x0" => "&#x" ) );
1512 }
1513
1514
1515 }
1516
1517 ?>